<template>
  <!-- 材料费 -->
  <section>
    <div style="text-align:right;">
      <el-select v-model="templateForm.curTemplate" style="width:300px;" value-key="template.id" filterable remote :remote-method="templatePage" clearable @clear="templatePage" @change="onChangeTemplate" placeholder="选择模板">
        <el-option v-for="(item,index) in templateForm.templateArr" :key="index" :value="item" :label="item.template.name"></el-option>
        <br>
        <pager v-model="templateForm.pager" small @change-pagenum="getTemplate"></pager>
      </el-select>
    </div>
    <br />
    <el-form :model="form" ref="form">
      <table class="table-box">
        <thead>
          <tr>
            <th>名称</th>
            <th>单位</th>
            <th>数量</th>
            <th>说明</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in form.list" :key="index">
            <td>
              <el-tooltip :disabled="!item.price" effect="dark" :content="'￥'+item.price" placement="top">
                <el-link :underline="false" type="primary">{{item.name}}</el-link>
              </el-tooltip>
            </td>
            <td>{{item.unit|changeAssist(unitEnum)}}</td>
            <td>
              <el-form-item :prop="'list.'+index+'.othersNum'" :rules="[rulesRequired,rulesNumber]">
                <el-input v-model.number="item.othersNum" type="number" :disabled="toDisabled(item)" style="width:100px"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-input v-model="item.remark" :disabled="toDisabled(item)"></el-input>
            </td>
            <td>
              <el-link v-if="!toDisabled(item)" :underline="false" class="vertical-middle" @click.prevent="onDelItem(item,index)">
                <i class="el-icon-delete"></i>
              </el-link>
            </td>
          </tr>
        </tbody>
      </table>
    </el-form>
    <div v-if="form.list.length == 0" style="color:#999;padding:10px 0;text-align:center;">
      <i class="iconfont iconwushuju" style="font-size:40px;"></i>
      <div>暂无数据</div>
    </div>
    <br />
    <div>
      <el-select v-model="curItem" value-key="id" filterable remote clearable @clear="pageOthersFee" :remote-method="pageOthersFee" @change="onChangeItem" placeholder="请选择其他收费" style="width:100%">
        <el-option v-for="(item,index) in otherFeeArr" :key="index" :label="item.name" :value="item"></el-option>
        <br />
        <pager v-model="pager" @change-pagenum="getPage"></pager>
      </el-select>
    </div>
    <br />
    <div class="form-tool">
      <div>
        <el-button type="primary" :loading="btnLoading" @click="onSubmit">保存</el-button>
      </div>
      <div>
        <el-button v-if="form.list.length>0&&!templateSave.t6" @click="dialogPrint=true">
          <i class="iconfont icondayin vertical-middle" style="font-size:20px;"></i>
          <span class="vertical-middle">打印其他收费请单</span>
        </el-button>
      </div>
    </div>
    <print v-model="dialogPrint" :list="form.list" :patientId="patientId" :cureId="cureId"></print>
  </section>
</template>
<script>
export default {
  components: {
    print: () => import("../_print/otherFee.vue")
  },
  computed: {
    templateSave() {
      return this.$store.state.doctorMZ.templateSave;
    },
    templateData() {
      return this.$store.state.doctorMZ.templateData;
    },
    unitEnum() {
      return this.$store.state.doctorMZ.enum.unitEnum;
    },
    patientId() {
      return this.$store.state.doctorMZ.patientId;
    },
    doctorId() {
      return this.$store.state.doctorMZ.doctorId;
    },
    deptId() {
      return this.$store.state.doctorMZ.deptId;
    },
    cureId() {
      return this.$store.state.doctorMZ.cureId;
    }
  },
  data() {
    return {
      pager: { pageSize: 10, pageNum: 1, total: 0 },
      searchForm: {
        queryStr: ""
      },
      dialogPrint: false,
      isOpenEdit: false,
      cureMedicalRelateId: "",
      btnLoading: false,
      form: {
        list: []
      },
      templateForm: {
        name: "",
        pager: { pageSize: 10, pageNum: 1, total: 0 },
        //选择的模板
        curTemplate: null,
        templateArr: []
      },
      curItem: "",

      otherFeeArr: [],
      rulesRequired: {
        required: true,
        message: "此项必填",
        trigger: ["blur", "change"]
      },
      rulesNumber: {
        message: "格式有误",
        type: "number",
        min: 1,
        trigger: ["blur", "change"]
      }
    };
  },
  created() {
    let th = this;
    th.getData();
  },
  mounted() {
    let th = this;
    th.templatePage();
    th.pageOthersFee();
  },
  methods: {
    onSubmit() {
      let th = this;
      if (!th.cureMedicalRelateId && th.form.list.length == 0) return;
      let update = function() {
        let j = {
          cureMedicalRelateId: th.cureMedicalRelateId,
          cureOthers: JSON.stringify(th.form.list)
        };
        th.btnLoading = true;
        th.$api
          .updatecureOthers(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("保存完成");
              th.getData("reset");
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
          })
          .catch(() => {
            th.btnLoading = false;
          });
      };
      let add = function() {
        let j = {
          cureMedicalRelateId: th.cureMedicalRelateId,
          cureOthers: JSON.stringify(th.form.list)
        };
        th.btnLoading = true;
        th.$api
          .addMultiplecureOthers(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("保存完成");
              th.getData("reset");
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
          })
          .catch(() => {
            th.btnLoading = false;
          });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          th.isOpenEdit = false;
          if (th.cureMedicalRelateId) update();
          else add();
        }
      });
    },
    //添加项目
    onChangeItem(obj) {
      let th = this;
      if (!obj) return;
      let j = {
        cureId: th.cureId,
        hpId: th.adminUser.hpId,
        patientId: th.patientId,
        deptId: th.deptId,
        doctorId: th.doctorId,
        othersId: obj.id,
        id: "",
        unit: obj.unit,
        name: obj.name,
        othersNum: "",
        price: obj.price,
        othersMoney: obj.retailPrice,
        remark: obj.remark,
        status: 0
      };
      th.addItem(j);
    },
    //选择模板
    onChangeTemplate(obj) {
      let th = this;
      if (!obj) return;
      let fn = function() {
        obj.baseTemplateAdviceBeans.forEach(item => {
          let j = {
            cureId: th.cureId,
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.deptId,
            doctorId: th.doctorId,
            othersId: item.adviceId,
            id: "",
            unit: item.unit,
            name: item.adviceDesc,
            othersNum: item.count,
            othersMoney: "",
            remark: item.remark,
            status: 0
          };
          th.addItem(j);
        });
      };
      fn();
    },
    onDelItem(obj, index) {
      let th = this;
      if (obj.id) {
        let j = {
          cureOthersId: obj.id
        };
        th.$api.cureOtherspreDelete(j).then(res => {
          if (res.executed && res.data) {
            th.form.list.splice(index, 1);
          } else {
            th.$message.warning(res.message);
          }
        });
      } else {
        th.form.list.splice(index, 1);
      }
    },
    //查询模板
    templatePage(name) {
      const th = this;
      th.templateForm.pager.pageNum = 1;
      th.templateForm.name = name;
      th.getTemplate();
    },
    //查询模板分页
    getTemplate() {
      let th = this;
      let j = {
        name: th.templateForm.name
      };
      Object.assign(j, th.templateForm.pager);
      th.$api.othersFeeTemplatepageOthersFee(j).then(res => {
        if (res.executed) {
          th.templateForm.templateArr = res.dataBody.list;
          th.templateForm.pager.total = res.dataBody.total;
        }
      });
    },
    getData(reset) {
      let th = this;
      let j = {
        cureId: th.cureId
      };
      th.$api.cureOtherslistcureId(j).then(res => {
        if (reset) {
          th.form.list = [];
        }
        res.data.forEach((data, index) => {
          if (index == 0) th.cureMedicalRelateId = data.cureMedicalRelateId;
          let j = {
            cureId: th.cureId,
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.deptId,
            doctorId: th.doctorId,
            othersId: data.cureOthersInfo.othersId,
            id: data.cureOthersInfo.id,
            unit: data.unit,
            name: data.name,
            status: data.cureOthersInfo.status,
            payStatus: data.payStatus,
            price: data.price ? Number.parseFloat(data.price) : 0,
            othersNum: data.cureOthersInfo.othersNum,
            othersMoney: "",
            remark: data.cureOthersInfo.remark
          };
          th.addItem(j);
        });
        th.$nextTick(function() {
          th.isOpenEdit = true;
          if (reset) {
            th.$store.commit("Set_templateSave", {
              key: "t6",
              value: false
            });
          }
        });
      });
    },
    getPage() {
      let th = this;
      let j = {
        hpId: th.adminUser.hpId,
        status: 0
      };
      Object.assign(j, th.searchForm, th.pager);
      th.$api.pageOthersFee(j).then(res => {
        if (res.executed) {
          if (res.dataBody.list) {
            th.otherFeeArr = res.dataBody.list;
            th.pager.total = res.dataBody.total;
          }
        }
      });
    },
    pageOthersFee(name) {
      let th = this;
      th.pager.pageNum = 1;
      th.searchForm.queryStr = name;
      th.getPage();
    },
    //添加项目
    addItem(json) {
      const th = this;
      if (typeof json.payStatus == "undefined") {
        json.payStatus = 2;
      }
      if (typeof json.status == "undefined") {
        json.status = 0;
      }
      if (json.payStatus == 2 && json.status == 0) {
        let data = th.form.list.find(d => {
          return (
            d.othersId == json.othersId &&
            json.payStatus == 2 &&
            json.status == 0
          );
        });
        if (data) return;
        th.form.list.push(json);
      } else {
        th.form.list.push(json);
      }
    },
    //清空未付款的数据
    delListData() {
      const th = this;
      let newArr = th.form.list.filter(d => {
        return d.payStatus != 2 || d.status == 1;
      });
      th.form.list = newArr;
    },
    //判断是否已执行
    toDisabled(obj) {
      if (obj.payStatus == 2 && obj.status == 0) {
        return false;
      } else {
        return true;
      }
    }
  },
  watch: {
    form: {
      deep: true,
      handler: function(n, o) {
        let th = this;
        if (!th.isOpenEdit) return;
        let bo = true;
        if (n.list.length == 0 && !th.cureMedicalRelateId) {
          bo = false;
        }
        //开启修改状态
        th.$store.commit("Set_templateSave", {
          key: "t6",
          value: bo
        });
      }
    },
    //监听大模板数据
    templateData: {
      deep: true,
      immediate: true,
      handler(n, o) {
        const th = this;
        let data = n.t6;
        //判断是否有值
        if (!data) {
          return;
        }
        //清空数据
        if (n.isEmpty) {
          th.delListData();
        }
        data.forEach(ele => {
          //添加数据
          let j = {
            cureId: th.cureId,
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.deptId,
            doctorId: th.doctorId,
            othersId: ele.id,
            id: "",
            unit: ele.unit,
            name: ele.name,
            price: ele.retailPrice,
            othersNum: 1,
            othersMoney: "",
            remark: ele.remark
          };
          j.othersMoney = j.price * j.othersNum;
          th.addItem(j);
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.item-box {
  background-color: #f3f3f3;
  margin: 0;
  padding: 9px 10px;
  border-radius: 7px;
  cursor: pointer;
}
.el-form-item {
  margin-bottom: 0;
}
</style>